import {
  shops,
  shopList
} from '~/tools/shops'
import {
  ds
} from '~/tools/data'
import {
  ui
} from '~/tools/ui'
import {
  pages
} from '~/tools/pages'
import {
  orderTool
} from '~/tools/oderTool'
import {
  dsx
} from '~/tools/datax'
Page({
  data: {
    item: {},
    oldItem: {}
  },
  async onLoad(options) {
    const data = JSON.parse(options.data)
    // console.log(data)
    ui.loading()

    const item = {
      shop: data.order.shop?.id,
      delivery: data.order.deliveryMan
    }
    this.setData({
      ...data,
      oldItem: item,
      item
    })
    this.initShops()
    this.loadDeliveryMan()
  },
  onShow() {

  },
  loadDeliveryMan() {
    const _ = ds.cmd
    ds.getAll('users', {
      role: _.eq('delivery').or(_.eq('master'))
    }, {
      role: 1,
      shops: 1,
      _openid: 1,
      personInfo: 1,
      wechat: 1
    }).then(res => {
      const nickNames = res.reduce((result, cur) => {
        result[cur._openid] = cur.personInfo?.nickName || cur.wechat || '无昵称'
        return result
      }, {})

      this.setData({
        deliveryList: res,
        nickNames
      })
      ui.loading(false)
    })
  },
  initShops() {
    const shopList = shops.getShopList()
    this.setData({
      shopNames: shops.getShopNames()
    })
  },
  shopTap() {
    const actions = shopList.map(ele => {
      return {
        name: ele.name,
        value: ele.id
      }
    })
    ui.actionSheetx(actions, (option) => {
      this.setData({
        'item.shop': option.value,
        'item.delivery': ''
      })
    })
  },
  deliveryTap() {
    const {
      item,
      deliveryList,
      nickNames,
      shopNames
    } = this.data
    const shopIds = (item.shop && [`${item.shop}`]) || shopList.map(ele => `${ele.id}`)
    const deliveryInShop = deliveryList.filter(user => {
      for (const id of user.shops) {
        if (shopIds.indexOf(`${id}`) >= 0) return true
      }
      return false
    })
    if (!deliveryInShop || deliveryInShop.length == 0) return ui.toast(false, '门店无配送员')

    ui.actionSheetx(deliveryInShop.map(user => {
      return {
        name: user.personInfo?.nickName || user.wechat || '无昵称',
        _openid: user._openid,
        shops: user.shops,
        _id: user._id
      }
    }), option => {
      // console.log(option)
      this.setData({
        'item.delivery': option._openid,
        'item.deliveryId': option._id
      })
      if (!item.shop) {
        this.setData({
          'item.shop': option.shops[0],
        })
      }
    })
  },
  backTap() {
    pages.back(pre => pre.onRefresh())
  },
  async saveTap() {
    const {
      item,
      order,
    } = this.data, that = this
    if (order.status == '配送中') return await ui.confirmx('订单配送中，请先通知配送员取消配送')
    if (order.status == '已送达' && !item.delivery)
      return await ui.confirmx('已送达订单必须填写配送员')
    if (!item.shop) return ui.toast(false, '请选择门店')
    if (!await ui.confirmx('确定更改吗？')) return

    ui.loading()
    orderTool.changeDeliveryShop({
      order,
      orderAddr: order.addr,
      shopId: item.shop,
      deliveryManOpenId: item.delivery,
      cb: (success, res) => {
        ui.loading(false)
        ui.toast(success, null, () => {
          success && ui.loading(true, '更新订单状态', () => {
            that.resetStatus((success, res) => {
              ui.loading(false)
              ui.toast(success, null, () => success && this.backTap())
            })
          })
        })
      }
    })
  },
  resetStatus(cb) {
    const {
      item,
      order,
    } = this.data
    // console.log(order)
    if (order.status == '待配送') {
      if (item.delivery)
        return orderTool.startDelivery(order, false, {
          _openid: item.delivery,
          _id: item.deliveryId
        }).then(res => {
          const success = res.result.errMsg.endsWith(":ok")
          if (cb) cb(success, res)
        }).catch(err => {
          if (cb) cb(false, err)
          console.error(err)
        })
    } else if (order.status == '已送达') {
      return dsx.cloudUpdate('orders', order._id, {
        deliveryMan: item.delivery
      }).then(res => {
        const success = res.result.errMsg.endsWith(":ok")
        if (cb) cb(success, res)
      }).catch(err => {
        if (cb) cb(false, err)
        console.error(err)
      })
    }
    if (cb) cb(true)
  },
})